<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use App\Model\NfcCard;
use App\Model\Normal;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\Redis;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;

class CardController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected NfcCard $nfcCard;



    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request):ResponseInterface
    {
        $page = $request->inputs(['page','limit','card_no','status']);

        $data['list'] = $this->nfcCard
            ->where(function ($query) use ($page){
                if($page['card_no']){
                    $query->where('card_no',$page['card_no']);
                }
                if($page['status']){
                    $query->where('status',$page['status']);
                }
            })->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get()->toArray();
        $data['total']= $this->nfcCard->count();
        return $this->success($data);
    }

    public function batchChange(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $page = $request->inputs(['ids', 'amount']);
        if ($page['ids']) {
            $page['ids'] = json_decode($page['ids'], true);
        } else {
            return $this->error(1001, '请先选择数据');
        }

        $this->nfcCard->whereIn('id', $page['ids'])
            ->update(['amount'=>$page['amount']]);
        return $this->success();
    }

    public function changeStatus(RequestInterface $request): ResponseInterface
    {
        $status = $request->input('status', 0, 'int');
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(code: 1001, msg: '缺失参数id');
        }
        $this->nfcCard->where('id', $id)->update(['status' => $status]);
        return $this->success(msg: '修改成功');
    }


    /**创建
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        $data = $request->post();
        if (array_key_exists('id',$data) && $data['id'] > 0) {
            $id = $data['id'];
            unset($data['id']);
            if(array_key_exists('updated_at', $data)){
                unset($data['updated_at']);
            }
            $this->nfcCard->where('id', $id)->update($data);
        } else {
            NfcCard::create($data);
        }
        return $this->success();
    }

    /**删除
     * @param RequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request):\Psr\Http\Message\ResponseInterface
    {
        try{
            $id = $request->input('id',0,'int');
            if (!$id) {
                return $this->error(ErrorCode::PARAMS_ERR);
            }
            $this->nfcCard->where('id',$id)->delete();
        return $this->success();
        }catch (\Exception $e){
            return $this->error(code:1001,msg:'操作繁忙请稍后重试');
        }
    }



    /**
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function batchCreate(RequestInterface $request): ResponseInterface
    {
        $file = $request->file('file');
//        $distributor = $request->input('distributor_id');
//        $is_new = $request->input('is_new',0);
//        if ($distributor == 'undefined') {
//            $distributor = '';
//        }
        $spreadsheet = IOFactory::load($file->getRealPath());
        // 选择第一个工作表
        $worksheet = $spreadsheet->getActiveSheet();
        // 获取最后一行和列
        $highestRow = $worksheet->getHighestRow();
        $highestColumn = $worksheet->getHighestColumn();
        $snExists = [];
        $iotSnExists = [];
        for ($row = 2; $row <= $highestRow; ++$row) {
            $rowData = [];
            for ($col = 'A'; $col <= $highestColumn; ++$col) {
                $rowData[] = $worksheet->getCell($col . $row)->getValue();
            }
            // 创建用户并插入数据库
            if ($rowData[0] && $rowData[1]) {
                if (strpos((string)$rowData[1], '；') !== false) {
                    $rowData[1] = explode('；', (string)$rowData[1]);
                } else {
                    $rowData[1] = explode(';', (string)$rowData[1]);
                }
                if (in_array($rowData[0], $snExists)) {
                    return $this->error(code: 1003, msg: '卡号' .$rowData[0] . '在上传文件中重复');
                }


                $snExists[] = $rowData[0];
            }
        }

        Db::beginTransaction();
        // 读取数据并插入数据库
        try {
            for ($row = 2; $row <= $highestRow; ++$row) {
                $rowData = [];
                for ($col = 'A'; $col <= $highestColumn; ++$col) {
                    $rowData[] = $worksheet->getCell($col . $row)->getValue();
                }
                // 创建用户并插入数据库
                if ($rowData[0] && $rowData[1]) {
                    $card = new NfcCard();
                    $card->card_no = $rowData[0];
                    $card->amount = round($rowData[1],2);
                    $check = NfcCard::where('card_no', $rowData[0])
                        ->first();
                    if ($check) {
                        return $this->error(code: 1002, msg: '卡号' . $rowData[0] . '已存在 请删除该数据重新上传');
                    }
                    $card->save();
                }
            }
            Db::commit();
            return $this->success(msg: '导入成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->error(code: 1002, msg: '导入失败，请检查文件内容是否符合规范' . $e->getMessage());
        }
    }

}
